from database import db
from flask import Flask
from sqlalchemy import text

from app.client_parkings import bp as bp_client_parkings
from app.clients import bp as bp_clients
from app.parkings import bp as bp_parkings


def create_app(
    db_uri: str = "sqlite:///project.db", echo: bool = True, testing: bool = False
):
    app = Flask(__name__)

    app.register_blueprint(bp_clients)
    app.register_blueprint(bp_parkings)
    app.register_blueprint(bp_client_parkings)

    app.config["SQLALCHEMY_DATABASE_URI"] = db_uri
    app.config["SQLALCHEMY_ECHO"] = echo
    app.config["TESTING"] = testing
    db.init_app(app)

    with app.app_context():
        from data import models  # for `db.create_all()` to work properly

        db.create_all()
        # Do not allow non-existent IDs as foreign keys:
        db.session.execute(text("pragma foreign_keys=on"))

    return app
